package com.eightbears.beboy.ui.merchant.activity;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopSelDataAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.ChartView;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.picker.DatePicker;
import com.eightbears.beboy.base.view.picker.DateTimePicker;
import com.eightbears.beboy.base.view.picker.utils.DateUtils;
import com.eightbears.beboy.entity.ShopSellDataEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPRUNDATA;
import static com.eightbears.beboy.base.util.CommonUtils.TimeStamp2Date;

public class ShopDataValActivity extends BaseActivity {

    private static final String TYPE_SELL_NUM = "1";
    private static final String TYPE_SELL_MONEY = "2";
    private static final String TYPE_DATE_DAY = "1";
    private static final String TYPE_DATE_MONTH = "2";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_sell_num)
    TextView tv_sell_num;
    @BindView(R.id.tv_sell_money)
    TextView tv_sell_money;
    @BindView(R.id.tv_total_num)
    TextView tv_total_num;
    @BindView(R.id.tv_total_balance)
    TextView tv_total_balance;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.cv_table)
    ChartView cv_table;
    @BindView(R.id.tv_sell_date_title)
    TextView tv_sell_date_title;
    @BindView(R.id.tv_sell_num_title)
    TextView tv_sell_num_title;
    @BindView(R.id.tv_sell_money_title)
    TextView tv_sell_money_title;
    @BindView(R.id.tv_date_title)
    TextView tv_date_title;
    @BindView(R.id.progress_wheel)
    ProgressWheel progress_wheel;

    private int currentMonth, currentDay, currentYear;
    private String startTime, endTime, dateType, dataType;
    private List<String> xValue = new ArrayList<>();                              //x轴坐标对应的数据
    private List<Integer> yValue = new ArrayList<>();                             //y轴坐标对应的数据
    private Map<String, Integer> value = new HashMap<>();                         //折线对应的数据
    private Map<Integer, ShopSellDataEntity.OnData> selDate = new HashMap<>();    //折线对应的数据
    private List<Integer> sellNums = new ArrayList<>();


    private UserEntity.Shop shop;
    private ShopSellDataEntity shopSellDataEntity;
    private ShopSelDataAdapter shopSelDataAdapter;
    private DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_data_val);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        shop = SPUtil.getUser().getData().getShops().get(0);
        tv_title.setText(R.string.text_shop_val_data);
        tv_sell_num.setSelected(true);

        initAdapter();
    }

    @Override
    protected void initData() {
        dataType = TYPE_SELL_NUM;
        dateType = TYPE_DATE_DAY;
        startTime = CommonUtils.getStartTimeOfMonth();
        endTime = CommonUtils.getEndTimeOfMonth();

        currentYear = CommonUtils.getDate()[0];
        currentMonth = CommonUtils.getDate()[1];
        currentDay = CommonUtils.getDate()[2];
        tv_date_title.setText(currentMonth + "/" + currentYear);
        initDatePick();
        getData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        cv_table.setOnItemClickListener(new ChartView.ChartClickListener() {
            @Override
            public void onChartClickListener(int position) {
                ShopSellDataEntity.OnData onData = selDate.get(position);
                tv_sell_date_title.setText(onData.getDate());
                tv_sell_num_title.setText(onData.getNum());
                tv_sell_money_title.setText(onData.getBalance());
                String num = String.format(getString(R.string.text_shop_data_add), onData.getNum());
                String money = String.format(getString(R.string.text_price), onData.getBalance());
                tv_total_num.setText(num);
                tv_total_balance.setText(money);

                shopSelDataAdapter.setNewData(onData.getEach_coupon());
            }
        });
    }

    private void initAdapter() {
        shopSelDataAdapter = new ShopSelDataAdapter();
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        rv_list.setAdapter(shopSelDataAdapter);
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_sell_num)
    void sellNum() {
        progress_wheel.setVisibility(View.VISIBLE);
        tv_sell_num.setSelected(true);
        tv_sell_money.setSelected(false);
        dataType = TYPE_SELL_NUM;
        getData();
    }

    @OnClick(R.id.tv_sell_money)
    void sellMoney() {
        progress_wheel.setVisibility(View.VISIBLE);
        tv_sell_num.setSelected(false);
        tv_sell_money.setSelected(true);
        dataType = TYPE_SELL_MONEY;
        getData();
    }

    @OnClick(R.id.ll_sel_data)
    void selDate() {
        datePicker.show();
    }

    private void initDatePick(){
        datePicker = new DatePicker(ShopDataValActivity.this, DateTimePicker.YEAR_MONTH);
        datePicker.setRangeStart(2016,1);
        datePicker.setRangeEnd(currentYear, 12);
        datePicker.setSelectedItem(currentYear, currentMonth);
        datePicker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
            @Override
            public void onDatePicked(String year, String month) {
                startTime = CommonUtils.getStartTime4YearMonth(Integer.parseInt(year), Integer.parseInt(month));
                endTime = CommonUtils.getEndTime4YearMonth(Integer.parseInt(year), Integer.parseInt(month));
                currentDay = DateUtils.calculateDaysInMonth(Integer.parseInt(month));
                currentMonth = Integer.parseInt(month);
                tv_date_title.setText(month + "/" + year);
                getData();
            }
        });
    }


    private void getData() {
        String url = URL_SHOPRUNDATA + shop.getShop_id() + "/businessData";

        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("start_at", startTime)
                .addParams("end_at", endTime)
                .addParams("type", dataType)
                .addParams("date_type", dateType)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                progress_wheel.setVisibility(View.GONE);
                shopSellDataEntity = GsonUtil.fromJson(response, ShopSellDataEntity.class);
                if (shopSellDataEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    setSellData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                progress_wheel.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopDataValActivity.this, status_error);
            }
        });
    }


    private void setSellData() {
        String totalPurchases = String.format(getString(R.string.text_shop_data_add),
                shopSellDataEntity.getData().getTotal_purchases());
        tv_num.setText(shopSellDataEntity.getData().getTotal_purchases());
        tv_money.setText(shopSellDataEntity.getData().getTotal_verify_balance());
        tv_total_num.setText(totalPurchases);
        tv_total_balance.setText(shopSellDataEntity.getData().getTotal_balance());

        initCvTable();
    }

    private void initCvTable() {
        xValue.clear();
        value.clear();
        yValue.clear();
        sellNums.clear();
        List<ShopSellDataEntity.OnData> onDatas = shopSellDataEntity.getData().getOn_date();
        for (int i = 0; i < currentDay; i++) {
            selDate.put(i, new ShopSellDataEntity.OnData(
                    currentMonth + "月" + (i + 1) + "日",
                    "0", "0", "0", "0"
            ));
            xValue.add(String.valueOf(i));
            value.put(String.valueOf(i), 0);
            for (int j = 0; j < onDatas.size(); j++) {
                String currentDate = CommonUtils.Date2TimeStamp(onDatas.get(j).getDate(), "yyyy-MM-dd");
                String currentDay = TimeStamp2Date(currentDate, "d");
                if (String.valueOf(i + 1).equals(currentDay)) {
                    selDate.put(i, onDatas.get(j));
                    value.put(String.valueOf(i), Integer.valueOf(onDatas.get(j).getNum()));
                    sellNums.add(Integer.parseInt(onDatas.get(j).getNum()));
                }
            }
        }

        if(sellNums.size() > 0) {
            for (int i = 0; i < getYLineVal(sellNums) / 10; i++) {
                yValue.add(i * 2);
            }
        } else {
            yValue.add(0);
        }


        cv_table.setValue(value, xValue, yValue);
        cv_table.setSelectIndex(1);
    }


    private int getYLineVal(List<Integer> sellNum) {
        int maxVal = Collections.max(sellNum);
        return maxVal % 100 == 0 ? maxVal : (maxVal / 100 + 1) * 100;
    }

}
